﻿using System.Collections.Generic;
using System.Linq;
using Fujitsu.JiraAnalysis.DAL;
using Fujitsu.JiraAnalysis.TrackingSystemAdapter;
using Fujitsu.JiraAnalysis.ReplicationService.SynchronizeExceptions;
using Fujitsu.JiraAnalysis.JiraRPC;

namespace Fujitsu.JiraAnalysis.ReplicationService.Synchronize
{
    public interface IIssuesTypesSync
    {
        void StartSync(ITrackSystemInfo adapter, Project project);
    }
    class IssuesTypesSync : SyncBase<RemoteIssueType, IssueTypeMapping>
    {
        IssuesTypeStorage issueTypeStorage = new IssuesTypeStorage();

        protected override SyncException GetSyncException(string projectName, int projectId, string projectKey)
        {
            return new IssueTypeSyncException(projectName, projectId, projectKey);
        }

        protected override List<IssueTypeMapping> GetStorageItems(int projectId)
        {
            return issueTypeStorage.GetIssueTypesMappingOfProject(projectId);
        }

        protected override List<RemoteIssueType> GetTrackSystemInfoItems(Project project, ITrackSystemInfo adapter)
        {
            return adapter.GetIssueTypesForProjectKey(project.ProjectKey);
        }

        protected override IssueTypeMapping FindMatchInStorage(List<IssueTypeMapping> storageItems, RemoteIssueType trackSystemInfoItem, int projectId)
        {
            return storageItems.FirstOrDefault(i => i.JiraTypeID.ToString() == trackSystemInfoItem.id && i.ProjectID == projectId);
        }

        protected override void Update(RemoteIssueType trackSystemItem, IssueTypeMapping issueTypeMapping)
        {
            if (issueTypeMapping.Name == trackSystemItem.name)
                return;
            issueTypeStorage.UpdateResolutionName(issueTypeMapping.ProjectID, issueTypeMapping.JiraTypeID, trackSystemItem.name);
        }
    }
}
